package com.block.source.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSONObject;
import com.block.common.exception.NotifyExceptionService;
import com.block.common.model.dto.CountInfoDTO;
import com.block.common.model.vo.ResultInfoVO;
import com.block.common.service.ICountCommonService;
import com.block.common.service.LogFactory;
import com.block.datapush.form.service.IDataPushFormService;
import com.block.datapush.model.result.SpePushResut;
import com.block.datapush.special.service.IDataPushSelfSpecialService;
import com.block.datapush.special.service.IDataPushSourceSpecialService;
import com.block.datapush.special.service.ISpecialCostomInfoService;
import com.block.db.entity.MemberExtInfo;
import com.block.db.entity.SourceBaseInfo;
import com.block.db.entity.SourceRecordInfo;
import com.block.db.model.param.SpeItemInfoParam;
import com.block.source.enums.DataActionEnum;
import com.block.source.enums.SettleTypeEnum;
import com.block.source.service.ISourceDataAddupService;
import com.block.source.service.ISourceHandleImportDataService;
import com.block.source.service.ISourceRecordInfoService;
import com.block.test.reqbean.source.ImportData;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Locale;

@Service
public class SourceHandleImportDataServiceImpl implements ISourceHandleImportDataService {

    private static Logger log = LogFactory.getSourceLog();

    @Autowired
    IDataPushSourceSpecialService dataPushSpecialService3;
    @Autowired
    ISourceRecordInfoService sourceRecordInfoService;
    @Autowired
    ISourceDataAddupService sourceDataAddupService;
    @Autowired
    IDataPushFormService dataPushFormService;
    @Autowired
    ICountCommonService countCommonService;
    @Autowired
    IDataPushSelfSpecialService dataPushSpecialService2;
    @Autowired
    ISpecialCostomInfoService specialCostomInfoService;
    @Autowired
    NotifyExceptionService notifyExceptionService;

    @Override
    public ResultInfoVO handleImportDataInfo(SourceBaseInfo sourceBaseInfo, ImportData importData) {

        // 1.检查手机号md5 是否一致
        SourceRecordInfo recordInfo = sourceRecordInfoService.getById(importData.getTradeNo());
        if (ObjectUtil.isEmpty(recordInfo)){
            return ResultInfoVO.error("tradeNo值错误");
        }

        String mobileMd5 = SecureUtil.md5(importData.getMobile()).toLowerCase(Locale.ROOT);
        if (!StrUtil.equals(mobileMd5, recordInfo.getMobileMd5())){
            return ResultInfoVO.error("手机号md5不一致");
        }

        // 2.数据更新
        boolean updateRes = sourceRecordInfoService.updateRecordInfo(recordInfo, importData);
        if (!updateRes){
            return ResultInfoVO.error("数据入库失败");
        }

        // 生成新的memberExtInfo 信息
        MemberExtInfo memberExtInfo = sourceRecordInfoService.saveNewMemExtInfo(sourceBaseInfo, recordInfo.getId());
        if (ObjectUtil.isEmpty(memberExtInfo)){
            return ResultInfoVO.error("入库失败");
        }

        // 测试标志，
        if (ObjectUtil.equals(sourceBaseInfo.getPushFlag(), Integer.valueOf(0))){
            JSONObject returnData = new JSONObject();
            returnData.put("message", "测试对接成功tradeNo："+recordInfo.getId());
            returnData.put("tradeNo", recordInfo.getId()+"");
            returnData.put("pushSuccess", true);

            SourceRecordInfo updateEntity = new SourceRecordInfo();
            updateEntity.setId(recordInfo.getId());
            updateEntity.setStatus(3);
            updateEntity.setMessage("测试入库成功，不推送");
            sourceRecordInfoService.updateById(updateEntity);

            return ResultInfoVO.success(returnData);
        }

        sourceDataAddupService.saveOrUpdateDataAddupInfo(recordInfo.getDateInfo(), DataActionEnum.REGISTER, sourceBaseInfo,  null);
        // 3.数据推送
        /**
         * 机构价格过滤
         * 根据结算方式，设置推送金额
         */
        BigDecimal priceAmount = recordInfo.getPriceAmount();
        SpeItemInfoParam speItemInfoParam = new SpeItemInfoParam();
        speItemInfoParam.setPriceAmount(priceAmount);

        // 根据线索信息，进行推送
        SpePushResut spePushResut = dataPushSpecialService3.dataPushHandle(memberExtInfo, speItemInfoParam);

        if (ObjectUtil.equals(sourceBaseInfo.getSettleFlag(), SettleTypeEnum.PUSH_SETTLE.getValue())){
            // 推送成功结算
            if (spePushResut.isSettleFlag()){
                // 推送成功

                SourceRecordInfo updateEntity = new SourceRecordInfo();
                updateEntity.setId(recordInfo.getId());
                updateEntity.setStatus(1);
                updateEntity.setUid(String.valueOf(memberExtInfo.getUid()));
                updateEntity.setSpeInfoId(String.valueOf(spePushResut.getSpeInfoId()));
                updateEntity.setPushPriceAmount(spePushResut.getSpeItemAmount());
                updateEntity.setMessage("推送成功");
                sourceRecordInfoService.updateById(updateEntity);

                recordInfo.setPushPriceAmount(spePushResut.getSpeItemAmount());

                sourceDataAddupService.saveOrUpdateDataAddupInfo(recordInfo.getDateInfo(), DataActionEnum.PUSH, sourceBaseInfo,  recordInfo);

                CountInfoDTO countInfoDTO = new CountInfoDTO(memberExtInfo.getChannelCode());
                countInfoDTO.setSourceCount(1);// 计算成本
                countInfoDTO.setSourceCost(recordInfo.getBaseAmount());// 计算成本
                countCommonService.calculateDataInfo2(countInfoDTO);

                JSONObject resultData = new JSONObject();
                resultData.put("tradeNo", String.valueOf(recordInfo.getId()));
                resultData.put("pushSuccess", true);
                resultData.put("itemInfo", String.valueOf(spePushResut.getSpeInfoId()));
                return ResultInfoVO.success(resultData);
            }

        }else if (ObjectUtil.equals(sourceBaseInfo.getSettleFlag(), SettleTypeEnum.REGISTER_SETTLE.getValue())){
            // 注册结算
            if (spePushResut.isSettleFlag()){
                SourceRecordInfo updateEntity = new SourceRecordInfo();
                updateEntity.setId(recordInfo.getId());
                updateEntity.setStatus(1);
                updateEntity.setUid(String.valueOf(memberExtInfo.getUid()));
                updateEntity.setSpeInfoId(String.valueOf(spePushResut.getSpeInfoId()));
                updateEntity.setPushPriceAmount(spePushResut.getSpeItemAmount());
                updateEntity.setMessage("推送成功");
                sourceRecordInfoService.updateById(updateEntity);

                recordInfo.setPushPriceAmount(spePushResut.getSpeItemAmount());

                sourceDataAddupService.saveOrUpdateDataAddupInfo(recordInfo.getDateInfo(), DataActionEnum.PUSH, sourceBaseInfo,  recordInfo);
            }

            CountInfoDTO countInfoDTO = new CountInfoDTO(memberExtInfo.getChannelCode());
            countInfoDTO.setSourceCount(1);// 计算成本
            countInfoDTO.setSourceCost(recordInfo.getBaseAmount());// 计算成本
            countCommonService.calculateDataInfo2(countInfoDTO);

            JSONObject resultData = new JSONObject();
            resultData.put("tradeNo", String.valueOf(recordInfo.getId()));
            resultData.put("pushSuccess", true);
            return ResultInfoVO.success(resultData);
        }


        /**
         * 没有推送出去，推给表单/异步推送
         */
        dataPushFormService.dataPushHandle(memberExtInfo);

        SourceRecordInfo updateEntity = new SourceRecordInfo();
        updateEntity.setId(recordInfo.getId());
        updateEntity.setStatus(2);
        updateEntity.setUid(String.valueOf(memberExtInfo.getUid()));
        updateEntity.setMessage(spePushResut.getMessage());
        sourceRecordInfoService.updateById(updateEntity);

        return ResultInfoVO.error("推送失败");
    }

}
